package com.yami.shop.otherservice;

import com.yami.shop.bean.dto.UserVipLevelDto;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.OrderRefund;
import com.yami.shop.bean.model.User;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.OrderRefundService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * UserVipLevel 自动升级(三级分销功能)
 */
@Service
public class UserVipLevelUpgradeService {
    @Autowired
    private UserService userService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderRefundService orderRefundService;

    /**
     * 自动升级下单用户所有上级的等级
     * @param uid
     */
    public void autoUpgradeAllHigherLevel(String uid) {
        List<User> allHigherLevelUser = userService.getAllHigherLevelUser(uid);
        List<User> existOrderUser=new ArrayList<>();
        for(User user:allHigherLevelUser){
            Integer userProdOrderQuantity = getUserProdOrderQuantity(user.getUserId());
            //至少存在一单的,才可以分配vip等级
            if(userProdOrderQuantity > 0){
                existOrderUser.add(user);
            }
        }

        //自动设置等级
        for(User user:existOrderUser){
            autoUpgrade(user.getUserId());
        }
    }

    /**
     * 获取指定用户的下单数量
     * @param uid
     * @return
     */
    public Integer getUserProdOrderQuantity(String uid) {
        String enableDistributionProdIds = this.getValueByConfig("enable_distribution_prod_ids");
        List<String> prodIds = Arrays.asList(StringUtils.split(enableDistributionProdIds, ","));
        List<Order> list = orderService.lambdaQuery().select(Order::getOrderNumber).eq(Order::getUserId, uid)
                .eq(Order::getIsPayed,1)//已支付
                .list();

        List<String> collect = list.stream().map(o -> o.getOrderNumber()).collect(Collectors.toList());

        //下单数量
        Integer orderQuantity=0;

        for(String orderNumber:collect){
            List<OrderItem> list1 = orderItemService.lambdaQuery()
                    .select(OrderItem::getOrderItemId,OrderItem::getProdCount)
                    .eq(OrderItem::getOrderNumber, orderNumber)
                    .in(OrderItem::getProdId, prodIds).list();
            //共下单了几个
            int sum1 = list1.stream().mapToInt(i -> i.getProdCount()).sum();
            for(OrderItem item:list1){
                List<OrderRefund> list2 = orderRefundService.lambdaQuery()
                        .select(OrderRefund::getGoodsNum)
                        .eq(OrderRefund::getOrderItemId, item.getOrderItemId())
                        .eq(OrderRefund::getReturnMoneySts, 1)//退款成功的
                        .list();

                //本个子订单共退款成功了几单
                int sum = list2.stream().mapToInt(r -> r.getGoodsNum()).sum();

                //本次订单还剩几单没有被退款
                int i = sum1 - sum;
                orderQuantity = orderQuantity +  i;
            }
        }

        return orderQuantity;
    }

    /**
     * 自动计算下单量,设置等级
     * @param uid
     */
    public void autoUpgrade(String uid) {
        String enableDistributionProdIds = this.getValueByConfig("enable_distribution_prod_ids");
        List<String> prodIds = Arrays.asList(StringUtils.split(enableDistributionProdIds, ","));

        //获取自己以下所有用户
        List<User>  list0=userService.getLowerLevel(uid,new ArrayList<>());
        list0.add(userService.getById(uid));//加上自己


        List<String> collect1 = list0.stream().map(u -> u.getUserId()).collect(Collectors.toList());

        //查询用户当前下单数量
        List<Order> list = orderService.lambdaQuery().select(Order::getOrderNumber).in(Order::getUserId, collect1)
                .eq(Order::getIsPayed,1)//已支付
                .list();

        List<String> collect = list.stream().map(o -> o.getOrderNumber()).collect(Collectors.toList());

        //下单数量
        Integer orderQuantity=0;

        for(String orderNumber:collect){
            List<OrderItem> list1 = orderItemService.lambdaQuery()
                    .select(OrderItem::getOrderItemId,OrderItem::getProdCount)
                    .eq(OrderItem::getOrderNumber, orderNumber)
                    .in(OrderItem::getProdId, prodIds).list();
            //共下单了几个
            int sum1 = list1.stream().mapToInt(i -> i.getProdCount()).sum();
            for(OrderItem item:list1){
                List<OrderRefund> list2 = orderRefundService.lambdaQuery()
                        .select(OrderRefund::getGoodsNum)
                        .eq(OrderRefund::getOrderItemId, item.getOrderItemId())
                        .eq(OrderRefund::getReturnMoneySts, 1)//退款成功的
                        .list();

                //本个子订单共退款成功了几单
                int sum = list2.stream().mapToInt(r -> r.getGoodsNum()).sum();

                //本次订单还剩几单没有被退款
                int i = sum1 - sum;
                orderQuantity = orderQuantity +  i;
            }
        }

        /**
         * 验证等级是否需要升级
         */
        User byId1 = userService.getById(uid);
        if(byId1.getVipLevel() != null){
            if(orderQuantity >= 25 ){
                if(byId1.getVipLevel() == 2){
                    //等级不需要变动
                    return;
                }
            }else if(orderQuantity >= 5){
                if(byId1.getVipLevel() == 1){
                    //等级不需要变动
                    return;
                }
            }else if(orderQuantity >= 1){
                if(byId1.getVipLevel() == 0){
                    //等级不需要变动
                    return;
                }
            }
        }


        List<UserVipLevelDto> higherLevelVip = userService.getHigherLevelVip(uid);

        if(orderQuantity >= 25 ){
            //svip
            UserVipLevelDto user2 = higherLevelVip.stream().filter(d -> d.getVipLevel()!= null && d.getVipLevel() == 2).findFirst().orElse(null);
            if (user2 != null){
                //升级时发现上面有svip用户
                User byId = userService.getById(user2.getId());

                User user=new User();
                user.setUserId(uid);
                user.setHigherLevelUid(byId.getHigherLevelUid());
                user.setVipLevel(2);//svip
                userService.updateById(user);

                //清除之前的关系
                userService.lambdaUpdate().set(User::getReward2YuanUid,null).eq(User::getReward2YuanUid,uid).update();

                User user1=new User();
                user1.setUserId(byId.getUserId());
                user1.setReward2YuanUid(uid);
                userService.updateById(user1);
            }else{
                User user=new User();
                user.setUserId(uid);
                user.setVipLevel(2);//svip
                userService.updateById(user);
            }
        }else if(orderQuantity >= 5){
            //vip
            UserVipLevelDto user1 = higherLevelVip.stream().filter(d -> d.getVipLevel()!= null && d.getVipLevel() == 1).findFirst().orElse(null);
            if (user1 != null){
                //升级时发现上面有svip用户
                User byId = userService.getById(user1.getId());

                User user=new User();
                user.setUserId(uid);
                user.setHigherLevelUid(byId.getHigherLevelUid());
                user.setVipLevel(1);//vip
                userService.updateById(user);

                //清除之前的关系
                userService.lambdaUpdate().set(User::getReward2YuanUid,null).eq(User::getReward2YuanUid,uid).update();

                User user2=new User();
                user2.setUserId(byId.getUserId());
                user2.setReward2YuanUid(uid);
                userService.updateById(user2);
            }else{
                User user=new User();
                user.setUserId(uid);
                user.setVipLevel(1);//vip
                userService.updateById(user);
            }
        }else if(orderQuantity >= 1){
            //普通会员
            UserVipLevelDto user0 = higherLevelVip.stream().filter(d -> d.getVipLevel()!= null && d.getVipLevel() == 0).findFirst().orElse(null);
            if (user0 != null){
                //升级时发现上面有svip用户
                User byId = userService.getById(user0.getId());

                User user=new User();
                user.setUserId(uid);
                user.setHigherLevelUid(byId.getHigherLevelUid());
                user.setVipLevel(0);//普通会员
                userService.updateById(user);

                //清除之前的关系
                userService.lambdaUpdate().set(User::getReward2YuanUid,null).eq(User::getReward2YuanUid,uid).update();

                User user2=new User();
                user2.setUserId(byId.getUserId());
                user2.setReward2YuanUid(uid);
                userService.updateById(user2);
            }else{
                User user=new User();
                user.setUserId(uid);
                user.setVipLevel(0);//普通会员
                userService.updateById(user);
            }
        }
    }

    /**
     * 获取配置项
     * @param key
     * @return
     */
    public String  getValueByConfig(String key) {
        List<String> param_value = jdbcTemplate.query("select param_value from tz_sys_config where param_key = ? ", new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString("param_value");
            }
        }, key);

        if(param_value.isEmpty()){
            return null;
        }else{
            return param_value.get(0);
        }
    }
}
